package com.example.crm.dao.Impl;

import com.example.crm.dao.ICustomerDAO;
import com.example.crm.pojo.Customer;
import com.example.crm.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public  class CustomerDAOImpl implements ICustomerDAO {
    @Override
    public int insert(Customer c) throws SQLException {
        String sql = "insert into cst_customer value (null,?,?,?,?,?,?,?,?,?);";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        Object[] params = {c.getCust_name(),c.getCust_user_id(),c.getCust_create_id(),
                c.getCust_source(),c.getCust_industry(),c.getCust_level(),
                c.getCust_linkman(),c.getCust_phone(),c.getCust_mobile()
        };
        return runner.update(sql,params);
    }

    @Override
    public List<Customer> find() throws SQLException {
        String sql = "select * from cst_customer;";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        List<Customer> list = runner.query(sql,new BeanListHandler<>(Customer.class));
        return list;
    }

    @Override
    public int delete(long custId) throws SQLException {
        String sql = "delete from cst_customer where cust_id=?;";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        int result = runner.update(sql,custId);
        return result;
    }

    @Override
    public Customer findById(long custId) throws SQLException {
        String sql = "select * from cst_customer where cust_id=?;";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        Customer c = runner.query(sql,new BeanHandler<>(Customer.class),custId);
        return c;
    }

    @Override
    public int update(Customer c) throws SQLException {
        String sql = "update cst_customer set cust_name=?,cust_level=?," +
                "cust_source=?,cust_linkman=?,cust_phone=?,cust_mobile=? where cust_id=?;";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        Object[] params = {c.getCust_name(),c.getCust_level(),c.getCust_source(),
                c.getCust_linkman(),c.getCust_phone(),c.getCust_mobile(),
                c.getCust_id()};
        int result = runner.update(sql,params);
        return result;
    }
}
